<template>
  <el-dialog
    :title="!id?'添加角色':'编辑角色'"
    :visible="showDialog"
    width="30%"
    @close="closeDialog"
  >
    <!-- 表单 -->
    <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="roleForm.name" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="roleForm.description" />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="addRoelOK">{{ !id?'确定':'编辑' }}</el-button>
    </span>
  </el-dialog>

</template>

<script>
// 引入接口
import { addRoleApi, getRoleDetailApi, editRoelApi } from '@/api'
export default {
  name: 'AddRoel',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      id: ''
    }
  },
  methods: {
    // 调用父组件显示弹框
    addRoel() {
      this.$emit('addRole')
    },
    // 调用父组件关闭弹框
    closeDialog() {
      this.$emit('closeDialog')
      this.resetForm()
      this.id = ''
    },
    // 取消
    cancel() {
      this.closeDialog()
    },
    // 重置表单
    resetForm() {
      this.$refs.roleForm.resetFields()
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    // 添加角色
    async addRoelOK() {
      try {
        if (!this.id) {
          await addRoleApi(this.roleForm)
        } else {
          // console.log(this.roleForm)
          await editRoelApi(this.roleForm)
        }
        // 更新数据
        this.$emit('get-roleList')
        // 关闭弹框
        this.closeDialog()
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑角色
    async editRoel(id) {
      try {
        const res = await getRoleDetailApi(id)
        this.roleForm = res.data
        this.id = res.data.id
        // console.log(this.roleForm)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="less" scoped>

</style>
